package com.witdata.rabbit.service;

import com.witdata.rabbit.consumer.instance.InstanceConsumer;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Data
@Slf4j
public class InstanceMessageService {
    private SimpleMessageListenerContainer container;
    private InstanceConsumer instanceConsumer;
    private RabbitAdmin rabbitAdmin;

    @Autowired
    public InstanceMessageService(ConnectionFactory connectionFactory, InstanceConsumer instanceConsumer, RabbitAdmin rabbitAdmin) {
        this.rabbitAdmin = rabbitAdmin;
        this.instanceConsumer = instanceConsumer;
        this.container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setMessageListener(instanceConsumer);
    }

    public void addQueue(String queueName) {
        Queue queue = new Queue(queueName);
        rabbitAdmin.declareQueue(queue);
        container.addQueueNames(queueName);
        if (!container.isRunning()) {
            container.start();
        }
        log.info("正在监听{}队列！", queueName);
    }

    public void removeQueue(String queueName) {
        container.removeQueueNames(queueName);
        log.info("已经停止监听{}队列", queueName);
    }



}
